package 软件工程实验三.A1.A11;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;

public class DateUtils {
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);

    // 将字符串转换为Date
    public static Date parseDate(String dateString) throws ParseException {
        return dateFormat.parse(dateString);
    }

    // 将Date格式化为字符串
    public static String formatDate(Date date) {
        return dateFormat.format(date);
    }

    // 计算距离现在多少年
    public static int calculateYearsFromNow(Date startDate) {
        LocalDate startLocalDate = startDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        LocalDate now = LocalDate.now();
        Period period = Period.between(startLocalDate, now);
        return period.getYears();
    }
}
